<template>
  <div class="container">
    <editPageNew
      ref="editPage"
      :rightBtnArr="rightBtnArr"
      :stepConfig="stepConfig"
      :creatInfo="formData"
      :moreBtnArr="moreBtnArr"
      :showMore="pageType != 'add'"
      showTopTitle
    >
      <template slot="editPageTitle">
        <span class="title-code">{{ `维保计划 ${formData.code || ""}` }}</span>
      </template>
      <div class="plan-title">
        <div v-show="!showInput" class="name">
          <span style="color: red"></span>
          <span>{{ titleName }}</span>
          <el-link
            v-show="!unChangeable"
            style="font-size: 20px"
            icon="el-icon-edit-outline"
            @click="editTitle"
          ></el-link>
        </div>
        <div v-show="showInput" class="name-input">
          <!-- <label>参数组名称</label> -->
          <el-input
            type="text"
            v-model="titleName"
            maxlength="64"
            show-word-limit
            @blur="loseFocus"
            @change="userInputTitle"
            placeholder="请输入名称"
            clearable
            ref="mark"
            ><template slot="prepend"
              >名称</template
            ></el-input
          >
        </div>
      </div>
      <el-collapse v-model="activeNames" style="padding-right: 10px">
        <el-collapse-item name="1">
          <template slot="title"> 计划信息 </template>
          <editForm
            :formConfig="basicConfig"
            ref="basicForm"
            :formData="formData"
          >
            <template #timeNum="{ editFormInfo }">
              <div class="dayInput">
                <el-input-number
                  style="flex: 4; margin-right: 20px"
                  size="mini"
                  v-model="editFormInfo.timeNum"
                  :step="1"
                  :min="0"
                  :disabled="unChangeable"
                  controls-position="right"
                  placeholder="请输入"
                  class="w100"
                ></el-input-number>
                <el-select
                  style="flex: 1"
                  size="mini"
                  v-model="editFormInfo.timePeriod"
                  placeholder="请选择"
                  :disabled="unChangeable"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </div>
            </template>
          </editForm>
        </el-collapse-item>
        <el-collapse-item name="2" v-if="isShowOperateForm">
          <template slot="title"> 作业表单 </template>
          <operate-form
            ref="operateForm"
            :operateForm="formData"
            :hideBtn="unChangeable"
            :deptIds="deptIds"
          ></operate-form>
        </el-collapse-item>
        <el-collapse-item name="3" v-if="isShowDispatch">
          <template slot="title"> 派工信息 </template>
          <dispatchInfo
            ref="dispatchInfo"
            :dispatchInfo="formData.dispatch"
            :unEdit="unChangeable"
          ></dispatchInfo>
        </el-collapse-item>
        <el-collapse-item name="4" v-if="isShowTimer">
          <template slot="title"> 定时器信息 </template>
          <timerInfo
            ref="timerInfo"
            :disabled="unChangeable"
            :cronTask="formData.cronTask"
          ></timerInfo>
        </el-collapse-item>
        <el-collapse-item name="5" v-if="status > 0">
          <template slot="title">
            <span class="titleLine"></span>
            审批信息
          </template>
          <workFlow
            :isDetails="pageType == 'details'"
            :currentFlowData="formData"
            ref="workFlow"
            :beforeSubmit="beforeSubmit"
            @submitSuccess="workFlowSuccess"
          ></workFlow>
        </el-collapse-item>
      </el-collapse>
    </editPageNew>
    <dialogPublic
      title="提交"
      :show.sync="show"
      @doClose="() => (show = false)"
      :fullscreen="true"
      :noFootBtn="true"
      appendTobody
    >
      <workFlow
        v-if="show"
        :isDetails="pageType == 'query'"
        workflowCode="maintain_plan"
        :currentFlowData="formData"
        :beforeSubmit="beforeSubmit"
        :isInit="isInit"
        ref="workFlow"
        @submitSuccess="workFlowInitSuccess"
      ></workFlow>
    </dialogPublic>
    <dialogPublic
      title="已下发工单"
      :show.sync="showOrder"
      v-if="showOrder"
      @doClose="() => (showOrder = false)"
      noFootBtn
      :fullscreen="true"
      appendTobody
    >
      <orderList showType="plan" ordeType="maintain" :planId="formData.id" ref="orderList" />
    </dialogPublic>
  </div>
</template>
<script>
import {
  addOrUpdateMaintainPlan,
  queryMaintainPlanDetail,
  deleteMaintainPlan,
  startOrStopPlan,
  issuePlan,
} from "@/api/productionPlan/maintenancePlan.js";
import operateForm from "../maintenancePlan/operateForm.vue";
import dispatchInfo from "../maintenancePlan/dispatchInfo.vue";
import timerInfo from "../maintenancePlan/timerInfo.vue";
import orderList from "@/views/orderManagement/normalMaintenance/index.vue"
export default {
  components: {
    dispatchInfo,
    operateForm,
    timerInfo,
    orderList
  },
  data() {
    return {
      showOrder:false,
      activeNames: ["1", "2", "3", "4", "5"],
      titleName: "",
      showInput: false,
      userInput: false,
      show: false,
      isInit: true,
      isShowOperateForm: false,
      isShowDispatch: false,
      isShowTimer: false,
      workFlowId: "",
      creatInfo: {},
      moreBtnArr: [
        {
          text: "操作记录",
          methods: () => {
            this.$refs.editPage.showOperate();
          },
        },
        {
          text: "已下发工单",
          methods: () => {
            this.showOrder = true;
          },
        },
      ],
      beforeSubmit: {
        methods: (data) => {
          return new Promise(async (resolve, reject) => {
            try {
              if (data.operation == "32") {
                const paramsData = await this.$refs.basicForm.getFormData();
                await addOrUpdateMaintainPlan(paramsData);
                resolve(true);
              } else {
                resolve(true);
              }
            } catch (error) {
              console.log(error);
              reject(error);
            }
          });
        },
      },
      basicConfig: {
        labelWidth: "120px",
        itemArr: [
          {
            label: "设备管理单位",
            prop: "deptManageName",
            propArr: "deptManageArr",
            idsStr: "deptManage",
            type: "dept-select",
            multiple: false,
            option: [],
            required: true,
            disabled: false,
            span: 8,
            methods: (row) => {
              this.deptIds = row.length > 0 ? [row[0].id] : [];
              this.producedTitle();
            },
          },
          {
            label: "专业",
            prop: "major",
            type: "select",
            required: true,
            disabled: false,
            span: 8,
            selectOption: this.$store.getters.dirtData("common_major"),
          },
          {
            label: "工作地点",
            prop: "address",
            propArr: "addressArr",
            idsStr: "addressId",
            type: "location-select",
            multiple: false,
            option: [],
            required: true,
            disabled: false,
            span: 8,
          },
          {
            label: "每单工期",
            prop: "timeNum",
            type: "text",
            required: true,
            span: 8,
          },
          {
            label: "提前下达(天)",
            prop: "delayDays",
            type: "el-number",
            isHide: false,
            required: true,
            min: 0,
            step: 1,
            stepStrictly: true,
            span: 8,
          },
          {
            label: "工单性质",
            prop: "nature",
            type: "select",
            required: true,
            span: 8,
            selectOption: [
              { label: "生产类", value: 1 },
              { label: "非生产类", value: 0 },
            ],
          },
          {
            label: "定时下达",
            prop: "isTimer",
            type: "select",
            required: true,
            selectOption: [
              { label: "是", value: 1 },
              { label: "否", value: 0 },
            ],
            span: 8,
            methods: (val) => {
              if (val.value) {
                this.basicConfig.itemArr[4].isHide = false;
                this.isShowTimer = true;
              } else {
                this.basicConfig.itemArr[4].isHide = true;
                this.isShowTimer = false;
              }
            },
          },
          {
            label: "是否派工",
            prop: "isDispatch",
            type: "select",
            required: true,
            span: 8,
            selectOption: [
              { label: "是", value: 1 },
              { label: "否", value: 0 },
            ],
            methods: (val) => {
              if (val.value) {
                this.isShowDispatch = true;
              } else {
                this.isShowDispatch = false;
              }
            },
          },
          {
            label: "是否需要作业表单",
            prop: "isNeed",
            type: "select",
            required: true,
            selectOption: [
              { label: "是", value: 1 },
              { label: "否", value: 0 },
            ],
            span: 8,
            methods: (val) => {
              if (val.value) {
                this.isShowOperateForm = true;
                this.$refs.basicForm.setFormItem("equipmentName", "");
                this.$refs.basicForm.setFormItem("equipmentId", "");
                this.$refs.basicForm.setFormItem("equipmentArr", []);
                this.$refs.basicForm.setFormItem("equipments", []);
                this.$refs.basicForm.setItemOption("equipmentName", []);
                this.basicConfig.itemArr[9].isHide = true;
              } else {
                this.isShowOperateForm = false;
                this.basicConfig.itemArr[9].isHide = false;
              }
            },
          },
          {
            label: "设备名称",
            prop: "equipmentName",
            idsStr: "equipmentId",
            filterConfig: ["filterManagerUnit"],
            managerUnit: [],
            multiple: true, //是否多选
            type: "device", //类型
            trigger: "change",
            beforeMethod: (formData, item) => {
              if (formData.deptManageName && formData.deptManageName != "") {
                item.managerUnit = [formData.deptManage];
                return true;
              } else {
                this.$message.warning("请先选择设备管理单位");
                return false;
              }
            },
            methods: (data, formData) => {
              let arr = data.map((item) => {
                const obj = {
                  equipmentId: item.id,
                  equipmentName: item.name,
                };
                return obj;
              });
              this.$refs.basicForm.setFormItem("equipments", arr);
            },
            span: 8,
            required: true,
            isHide: false,
            disabled: false,
          },
          {
            label: "工作内容",
            prop: "content",
            type: "textarea",
            required: true,
            span: 12,
            rows: 3,
            methods: (row) => {
              this.producedTitle();
            },
          },

          {
            label: "备注",
            prop: "desc",
            type: "textarea",
            rows: 3,
            required: false,
            span: 12,
          },
        ],
      },
      formData: {
        isTimer: 0,
        isDispatch: 0,
        isNeed: 0,
        timePeriod: "HOUR",
      },
      options: this.$store.getters.dirtData("time_period"),
      //不可更改
      status: 0,
      deptIds: [],
      planStatus: [0, 2, 1],
    };
  },
  computed: {
    rightBtnArr() {
      let arr = [
        {
          text: "提交",
          icon: "el-icon-video-play",
          hide:
            ["details", "perform", "add"].includes(this.pageType) ||
            [1, 2].includes(this.formData.status),
          content: "未授权功能",
          disabled: !this.$store.getters.isBtnAuth("enable"),
          methods: () => {
            this.doSubmit();
          },
        },
        {
          text: "手动下发",
          icon: "el-icon-refresh",
          hide:
            ["details", "perform", "add"].includes(this.pageType) ||
            this.formData.status != 1,
          content: "未授权功能",
          disabled: !this.$store.getters.isBtnAuth("issue"),
          methods: () => {
            this.issued();
          },
        },
        {
          text: "停用",
          icon: "el-icon-video-pause",
          hide:
            ["details", "perform", "add"].includes(this.pageType) ||
            this.formData.status != 1,
          content: "未授权功能",
          disabled: !this.$store.getters.isBtnAuth("deactivate"),
          methods: () => {
            this.DeactivatePlan();
          },
        },
        {
          text: "保存",
          icon: "el-icon-check",
          hide:
            ["details", "perform"].includes(this.pageType) ||
            [1, 2].includes(this.formData.status),
          content: "未授权功能",
          disabled: !this.$store.getters.isBtnAuth("save"),
          methods: () => {
            this.save("save");
          },
        },
        {
          text: "删除",
          icon: "el-icon-delete-solid",
          hide:
            ["perform", "details", "add"].includes(this.pageType) ||
            this.formData.status != 0,
          content: "未授权功能",
          disabled: !this.$store.getters.isBtnAuth("delete"),
          methods: () => {
            this.deleteId();
          },
        },
      ];
      return arr;
    },
    stepConfig() {
      let step = this.planStatus.indexOf(this.status);
      let obj = {
        nowStep: parseInt(step), //当前步骤，对应stepItem数组的下标，例如：0-步骤一、1-步骤二
        stepItem: ["草稿", "待审核", "已启用"],
      };
      return obj;
    },
    unChangeable() {
      return ["query", "detail"].includes(this.pageType) || this.status != 0;
    },
  },
  created() {
    this.init();
  },
  watch: {
    unChangeable: {
      handler(val) {
        if (val) {
          this.basicConfig.itemArr.map((i) => (i.disabled = true));
        } else {
          this.basicConfig.itemArr.map((i) => {
            i.disabled = false;
          });
        }
      },
    },
  },
  mounted() {
    if (this.pageType == "add") {
      this.producedTitle();
      let deptOption = [
        {
          label: this.formData.deptManageName,
          value: this.formData.deptManage,
          id: this.formData.deptManage,
          name: this.formData.deptManageName,
        },
      ];
      setTimeout(() => {
        this.$refs.basicForm.setItemOption("deptManageName", deptOption);
        this.$refs.basicForm.setFormItem(
          "deptManageArr",
          this.formData.deptManage
        );
      }, 0);
    }
  },
  methods: {
    init() {
      let { id } = this.$route.query;
      if (id) {
        this.pageType = this.$store.getters.isBtnAuth("edit")
          ? "edit"
          : "detail";
        this.getDetails(id);
        if (this.pageType == "detail") {
          this.basicConfig.itemArr.map((i) => (i.disabled = true));
          this.titleEdit = false;
        }
      } else {
        this.pageType = "add";
        this.showInput = true;
        this.basicConfig.itemArr[4].isHide = true;
        this.$set(
          this.formData,
          "deptManage",
          this.$store.getters.currentOrgInfo.id
        );
        this.$set(
          this.formData,
          "deptManageName",
          this.$store.getters.currentOrgInfo.name
        );
        this.deptIds = [this.$store.getters.currentOrgInfo.id];
      }
    },
    //编辑标题
    editTitle() {
      this.showInput = true;
      setTimeout(() => {
        this.$refs.mark.focus();
      }, 0);
    },
    //标题输入框失去焦点
    loseFocus() {
      if (this.titleName != "") {
        this.showInput = false;
      } else {
        this.showInput = true;
        this.$message.warning("标题不能为空");
      }
    },
    //手动输入标题
    userInputTitle(val) {
      if (val != "") {
        this.userInput = true;
      } else {
        this.userInput = false;
      }
    },
    //初始化标题生成方式
    initTitleInput(formData) {
      let title = `${formData.deptManageName}${formData.content}`;
      if (formData.name != title) {
        this.userInput = true;
      }
    },
    //生成标题
    producedTitle() {
      let formData = this.$refs.basicForm.getCurrentData();
      let title = `${formData.deptManageName || ""}${formData.content || ""}`;
      if (!this.userInput) {
        this.titleName = title;
      }
    },
    //获取标准详情
    getDetails(id) {
      queryMaintainPlanDetail({ id: id }).then((res) => {
        if (res.code == 200) {
          let data = res.data;
          this.creatInfo = res.data;
          this.status = data.status;
          this.titleName = data.name;
          this.workFlowId = data.billId;
          this.deptIds = [data.deptManage];
          this.isInit = data.currentNodeUserName ? false : true;
          if (!data.cronTask) {
            data.cronTask = {};
          }
          if (data.isTimer == 0) {
            this.basicConfig.itemArr[4].isHide = true;
          }
          this.isShowOperateForm = data.isNeed == 1 ? true : false;
          this.isShowDispatch = data.isDispatch == 1 ? true : false;
          this.isShowTimer = data.isTimer == 1 ? true : false;
          this.formData = data;
          if (!this.isShowOperateForm) {
            data.equipmentName = data.equipments
              .map((i) => i.equipmentName)
              .join(", ");
            data.equipmentId = data.equipments
              .map((i) => i.equipmentId)
              .join(", ");
          } else {
            this.basicConfig.itemArr[9].isHide = true;
          }
          let deptOption = [
            {
              label: this.formData.deptManageName,
              value: this.formData.deptManage,
              id: this.formData.deptManage,
              name: this.formData.deptManageName,
            },
          ];
          let addressOption = [
            {
              label: this.formData.address,
              value: this.formData.addressId,
              id: this.formData.addressId,
              name: this.formData.address,
            },
          ];
          setTimeout(() => {
            this.$refs.basicForm.setItemOption("deptManageName", deptOption);
            this.$refs.basicForm.setItemOption("address", addressOption);
            this.$refs.basicForm.setFormItem(
              "deptManageArr",
              this.formData.deptManage
            );
            this.$refs.basicForm.setFormItem(
              "addressArr",
              this.formData.addressId
            );
          }, 100);
        }
      });
    },
    //停用计划
    DeactivatePlan() {
      this.$confirm("停用维保计划会回退到草稿状态，确定要停用吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const params = {
            id: this.formData.id,
            startOrStop: false,
          };
          startOrStopPlan(params).then((res) => {
            if (res.code == 200) {
              this.$message.success("停用成功");
              this.$utils.addOperateLog(this.formData.id, "停用-维保计划");
              this.updateListData();
              this.getDetails(this.formData.id);
            }
          });
        })
        .catch((e) => {});
    },
    //下发
    issued() {
      this.$confirm("手动下发会生成正常维护工单，确定要下发吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          issuePlan({ id: this.formData.id }).then((res) => {
            if (res.code == 200) {
              this.$message.success("下发成功");
              this.$utils.addOperateLog(this.formData.id, "下发-维保计划");
              this.updateListData();
            }
          });
        })
        .catch((e) => {});
    },
    //删除维保计划
    deleteId() {
      this.$confirm("确定要删除选中数据吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteMaintainPlan({ planId: this.formData.id }).then((res) => {
            if (res.code === 200) {
              this.$message.success(res.description);
              this.$utils.addOperateLog(this.formData.id, "删除-维保计划");
              this.updateListData();
              this.$refs.editPage.closePage();
            }
          });
        })
        .catch((e) => {});
    },
    //提交
    doSubmit() {
      this.$confirm(`提交后数据将会自动保存，是否继续`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.save("submit");
        })
        .catch((e) => {});
    },
    //保存正常维护标准
    async save(type) {
      try {
        const paramsData = await this.$refs.basicForm.getFormData();
        if (this.titleName == "") {
          this.loseFocus();
        } else {
          paramsData.name = this.titleName;
          if (paramsData.isDispatch) {
            paramsData.dispatch = await this.$refs.dispatchInfo.getDispatchInfo();
          } else {
            delete paramsData.dispatch;
          }
          if (paramsData.isNeed) {
            let operate = await this.$refs.operateForm.getOperateInfo();
            paramsData.workReadys = operate.workReadys;
            paramsData.standards = operate.standards;
            paramsData.instructions = operate.instructions;
          } else {
            delete paramsData.workReadys;
            delete paramsData.standards;
            delete paramsData.instructions;
          }
          if (paramsData.isTimer) {
            paramsData.cronTask = this.$refs.timerInfo.getTimeInfo();
          } else {
            delete paramsData.delayDays;
            delete paramsData.cronTask;
          }
          addOrUpdateMaintainPlan(paramsData).then((res) => {
            if (res.code == 200) {
              this.$message.success(res.description);
              if (this.pageType == "add") {
                this.$utils.addOperateLog(res.data.id, "新建-维保计划");
                this.updateListData();
                let obj = {
                  id: res.data.id,
                  pageType: "edit",
                };
                this.$router.push({
                  query: obj,
                });
                setTimeout(() => {
                  this.$refs.editPage.closePage();
                }, 1000);
              } else if (type == "submit") {
                this.$utils.addOperateLog(
                  this.formData.id,
                  "修改并提交-维保计划"
                );
                this.show = true;
                this.getDetails(this.formData.id);
                this.updateListData();
              } else {
                this.$utils.addOperateLog(this.formData.id, "修改-维保计划");
                this.getDetails(this.formData.id);
                this.updateListData();
              }
            }
          });
        }
      } catch (error) {
        this.$message.warning(error);
      }
    },
    //验证定时任务是否可行
    async verification() {
      try {
        const paramsData = await this.$refs.basicForm.getFormData();
        await addOrUpdateMaintainPlan(paramsData);
      } catch (error) {
        console.log(error);
        throw error;
      }
    },
    updateListData() {
      /* 通过localStorage来实现浏览器不同窗口之间的通信 */
      let num = Math.floor(Math.random() * 1000) + 1; //产生随机数，保证每次的值都不一样
      localStorage.setItem("update", num); //设置localStorage里面的值，保证每次都会触发storage事件
    },
    //工作流成功后的回调函数
    workFlowSuccess() {
      this.updateListData();
      this.getDetails(this.formData.id);
      this.$refs.workFlow.initIframe();
    },
    //草稿状态工作流提交成功之后
    workFlowInitSuccess() {
      this.show = false;
      this.$utils.addOperateLog(this.formData.id, `提交了${this.title}`);
      this.updateListData();
      this.getDetails(this.formData.id);
    },
  },
};
</script>
<style lang="less" scoped>
.container {
  height: 100%;
  width: 100%;
  overflow: hidden;
  background-color: #ffffff;
  .TitleImg {
    margin-right: 2px;
    font-size: 22px;
  }
  .plan-title {
    height: 40px;
    margin: 0 0 10px 0;
    .name {
      font-size: 18px;
      padding: 0 10px;
      height: 40px;
      font-weight: bold;
      line-height: 40px;
      text-align: left;
      padding: 0 10px;
    }
    .name-input {
      width: 400px;
      height: 40px;
      line-height: 40px;
    }
  }
  .dayInput {
    height: 100%;
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
</style>
